import commands
import shutil
import pylab
import os

from optparse import OptionParser, OptionGroup

import utils

try:
    status = commands.get_statusoutput("convert")[0]
    if not status == 0:
        HAS_IMAGEMAGIK = False
        raise RuntimeError("You need to install the imagemagick library")
except:
    pass

def usage():
    print "Usage"

def main(dirname, fname, variable="q", varid=0, animfile="test", **kwargs):

    path = os.path.abspath( dirname )
    files = os.listdir( path )

    # get all the output files in the directory
    files = [f for f in files if f.startswith(fname) and f.endswith(".npz") ]

    # sort the files
    def _sort_func(x, y):
        """Sort the files correctly."""
        def _process(arg):
            a = os.path.splitext(arg)[0]
            return int(a[a.rfind('_')+1:])
        return cmp(_process(x), _process(y))

    files.sort(_sort_func)

    # create a temporary directory
    tmpdir = os.path.join(dirname, "plot") 
    utils.mkdir( tmpdir )

    # create the plots
    count = 0
    for f in files:
        f = os.path.join(path, f)
        g = utils.load(f)

        data = getattr(g, variable)
        pylab.plot( g.xc, data[varid] )

        pylab.savefig( os.path.join(tmpdir, "out_%03d.png"%(count)) )
        pylab.close()
        count += 1

    # create the animation
    animfile = animfile + ".gif"
    cmd = "convert -delay 20 -loop 0 %s/*.png %s "%(tmpdir, animfile)
    st = commands.getstatusoutput(cmd)[0]
    print st

if __name__ == "__main__":
    parser = OptionParser()

    fileopts = OptionGroup(parser, "File options ")

    fileopts.add_option("--directory", action="store", type="string",
                        dest="dir", default=".", help="""The directory with the output data files """)

    fileopts.add_option("--fname", action="store", type="string",
                         dest="fname", help="The base name for the data files")

    fileopts.add_option("--animfile", action="store", type="str",
                        dest="animfile", default="test", help="Output anim file name")

    dataopts = OptionGroup(parser, "Options for the data")

    dataopts.add_option("--variable", action="store", type="str",
                        dest="variable", default="q", help="Conserved or primitive variables")

    dataopts.add_option("--varid", action="store", type="int",
                        dest="varid", default=0, help="Index of the variable")

    plotopts = OptionGroup(parser, "Plotting options")

    plotopts.add_option("--title", action="store", type="str",
                        dest="title", default="", help="Title for the plot")

    plotopts.add_option("--xl", action="store", type="float",
                        dest="xl", help="Left end of the domain")

    plotopts.add_option("--xr", action="store", type="float",
                        dest="xr", help="Right end of the domain")

    plotopts.add_option("--yl", action="store", type="float",
                        dest="yl", help="Lower end of the domain")

    plotopts.add_option("--yu", action="store", type="float",
                        dest="yu", help="Upper end of the domain")

    # Add the option groups
    parser.add_option_group(fileopts)
    parser.add_option_group(dataopts)
    parser.add_option_group(plotopts)
    
    # parse the args
    options, args = parser.parse_args()

    if options.fname is None:
        raise RuntimeError("You must provide a file name")

    main(dirname = options.dir, fname = options.fname, variable=options.variable,
         varid=options.varid, animfile=options.animfile)    
